package com.jk.util.autotest.util;

import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * @author Administrator
 */
public class HttpUtilPlus {

    public static String interfaceUtil(String path, String data,boolean isDectRead){
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(3000);
        requestFactory.setReadTimeout(3000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        if(data == null || "".equals(data)){
            return doGet(restTemplate,path,isDectRead);
        }else {
            return doPost(restTemplate,path,data,isDectRead);
        }
    }

    private static String doGet(RestTemplate restTemplate,String path,boolean isDectRead){
        String defaultPath = path;
        try {
            if(isDectRead){
                path = new StringBuilder(path).append("&isDectRead=true").toString();
            }
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(path, String.class);
            return responseEntity.getBody();
        } catch (RestClientException e) {
            e.printStackTrace();
            System.out.println(path+"访问出错");
            return doGet(restTemplate,defaultPath,isDectRead);
        }
    }

    private static String doPost(RestTemplate restTemplate,String path,String data,boolean isDectRead){
        String defaultData = data;
        try {
            if(isDectRead){
                data = data.substring(0,data.length()-1);
                data = new StringBuilder(data).append(",\"isDectRead\":true}").toString();
            }
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(path,data,String.class);
            return responseEntity.getBody();
        } catch (RestClientException e) {
            e.printStackTrace();
            System.out.println(path+"访问出错");
            return doPost(restTemplate,path,defaultData,isDectRead);
        }
    }
}
